package web.controllers;

import dao.TaskDAO;
import domain.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import service.TaskManager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Алексей
 * Date: 07.04.13
 * Time: 20:50
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/task")
public class TaskController {

    @Autowired
    private TaskManager tm;

    @RequestMapping(method = RequestMethod.GET)
    public String listBuyers(Map<String, Object> model){
        model.put("tasks", tm.getTasks());
        return "task/list";
    }

    @RequestMapping(value = "/{action}", method = RequestMethod.GET)
    public String add(@PathVariable String action, Model model) {

        if (action.equals("add")) {
            model.addAttribute("buyer", new Task());
            return "task/edit";
        }
        return "redirect:/task";
    }

    @RequestMapping(value = "/{action}/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable String id, @PathVariable String action, Model model) {

        Task task = tm.getTask(Integer.parseInt(id));

        if (action.equals("delete")) {
            tm.delete(task.getId());
            return "redirect:/task";
        }

        if (action.equals("edit"))
            model.addAttribute("task", task);
        return "task/edit";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/add")
    public String add(@ModelAttribute("task") Task task) {
        tm.add(task.getName(),task.getDescription(), task.getDate());
        return "redirect:/task";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/edit/{id}")
    public String update(@PathVariable String id, @ModelAttribute("task") Task task) {
        tm.update(task.getId(), task.getName(), task.getDescription(), task.getDate(), task.getVersion());
        return "redirect:/task";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}
